package com.example.mooctao.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.mooctao.R;
import com.example.mooctao.UloginActivity;
import com.example.mooctao.util.DataUtil;
import com.example.mooctao.util.IndexViewModel;
import com.example.mooctao.util.MeViewModel;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//我的页面
public class MeFragment extends Fragment {

    private List<Map<String, Object>> data = new ArrayList<>();
    private MeViewModel viewModel;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_me, container, false);

        //点击登录跳转到登录界面
        v.findViewById(R.id.login_me_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContext(), UloginActivity.class));
            }
        });

        ListView meListView = v.findViewById(R.id.me_listview);
        //从ViewModel获取数据
        viewModel = new ViewModelProvider(this).get(MeViewModel.class);
        data = viewModel.getData() != null ? viewModel.getData() : new ArrayList<>();
        //初始化数据
        initData();

        String[] from = {"img", "txt"};
        int[] to = {R.id.image_listview, R.id.text_listview};
        //在Fragment中Context必须通过getContext()来获取
        SimpleAdapter adapter = new SimpleAdapter(getContext(), data, R.layout.me_menu_listview, from, to);

        meListView.setAdapter(adapter);

        return v;
    }
    //初始化数据
    private void initData() {
        if (data.isEmpty()) {
            for (int i = 0; i < DataUtil.me_imgs.length; i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("img", DataUtil.me_imgs[i]);
                map.put("txt", DataUtil.me_txts[i]);
                data.add(map);
            }
            viewModel.setData(data);
        }
    }


}
